<template>
  <div>
    <!-- -----------------------------------------------------基本信息-------------------------------------------------------------- -->
    <el-divider>基本信息</el-divider>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" inline label-width="120px">
      <div class="dialog_left">
        <el-form-item label="入库类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择" @change="handleSelect" :disabled="!innertexteFlag">
            <el-option v-for="(item, i) in purchaseOptionsList" :key="i" :label="item" :value="i">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采购单" prop="purchaseId" v-if="ruleForm.type == 0">
          <el-select v-model="ruleForm.purchaseId" placeholder="请选择采购单" @change="handleSelect">
            <el-option v-for="(item, i) in procurementOptionsList" :key="i" :label="item.purchaseNum"
              :value="item.purchaseId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入库仓库" prop="storehouseId">
          <el-cascader v-model="ruleForm.storehouseId" :options="storageOptionsList" @change="handleSelect"
            :props="{ expandTrigger: 'hover', label: 'storehouseName', value: 'storehouseId' }">
          </el-cascader>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </div>
      <!-- -----------------------------------------------------添加采购品【按钮】及弹框-------------------------------------------------------------- -->
      <div class="dialog_btn">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddPurchase">添加物料</el-button>
      </div>
      <Purchase ref="purchase_form" @click_create_submit="handleSlectList" />
      <!-- ---------------------------------------------------物料采购表格----------------------------------------------------------- -->
      <div class="dialog_table">
        <el-table :data="ruleForm.SubmitSelectList" style="width: 100%" max-height="455">
          <el-table-column label="序号" width="100">
            <template slot-scope="scope">
              <div> {{ scope.$index + 1 }} </div>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" width="160">
            <template slot-scope="{row}">
              <div> {{ row.materialNum || row.consPriceAndAmountVo.materialNum }} </div>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" width="160">
            <template slot-scope="{row}">
              <div> {{ row.materialName || row.consPriceAndAmountVo.materialName }} </div>
            </template>
          </el-table-column>
          <el-table-column label="物料类别" width="160">
            <template slot-scope="{row}">
              <div> {{ row.typeName || row.consPriceAndAmountVo.typeName }} </div>
            </template>
          </el-table-column>
          <el-table-column label="物料规格型号" width="160">
            <template slot-scope="{row}">
              <div v-if="innertexteFlag"> {{ row.model || '-' }} </div>
              <div v-if="!innertexteFlag"> {{ row.consPriceAndAmountVo && row.consPriceAndAmountVo.model || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" width="160">
            <template slot-scope="{row}">
              <div> {{ row.unitName || row.consPriceAndAmountVo && row.consPriceAndAmountVo.unitName }} </div>
            </template>
          </el-table-column>
          <el-table-column label="批次" width="160">
            <template slot-scope="scope">
              <el-form-item class="table_form_input" :prop="'SubmitSelectList.' + scope.$index + '.batch'"
                :rules="rules.batch">
                <el-input style="width:100%" v-model="scope.row.batch" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="overplusAmount" label="待入库数量" v-if="ruleForm.type == 0" width="160">
            <template slot-scope="{row}">
              <div> {{ row.overplusAmount || row.consPriceAndAmountVo.overplusAmount || 0 }} </div>
            </template>
          </el-table-column>
          <el-table-column width="160">
            <template slot="header">
              <div>入库数量
                <el-tooltip v-if="ruleForm.type == 0" content="入库数量不能大于待入库数量" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </div>
            </template>
            <template slot-scope="scope">
              <div v-if="innertexteFlag == true">
                <el-form-item class="table_form_input" :prop="'SubmitSelectList.' + scope.$index + '.amounts'"
                  :rules="rules.amounts">
                  <el-input-number style="width:100%" :min="1" :controls="false" @input.native="onInput0_100"
                    :max="ruleForm.type == 0 ? scope.row.overplusAmount : 9999999" v-model="scope.row.amounts" />
                </el-form-item>
              </div>
              <div v-if="innertexteFlag == false">
                <div v-if="!scope.row.amounts">
                  <el-form-item class="table_form_input">
                    <el-input-number style="width:100%" :min="0" :controls="false" @input.native="onInput0_100"
                      :max="ruleForm.type == 0 ? scope.row.consPriceAndAmountVo.overplusAmount : 9999999"
                      v-model="scope.row.amounts" />
                  </el-form-item>
                </div>
                <div v-if="scope.row.amounts">
                  <el-form-item class="table_form_input">
                    <!-- @change="handleAmount(scope.row.overplusAmount, scope.row.amount)" 采购时入库数量不允许大于待入库数量-->
                    <el-input-number style="width:100%" :min="1" :controls="false" @input.native="onInput0_100"
                      :max="ruleForm.type == 0 ? scope.row.overplusAmount : 9999999" v-model="scope.row.amounts" />
                  </el-form-item>
                </div>
              </div>

            </template>
          </el-table-column>
          <el-table-column prop="price" label="采购单价（元）" width="160">
            <template slot-scope="scope">
              <div v-if="innertexteFlag == true">
                <div v-if="scope.row.price"> {{ scope.row.price }} </div>
                <el-form-item v-else class="table_form_input" :prop="'SubmitSelectList.' + scope.$index + '.prices'"
                  :rules="rules.prices">
                  <el-input-number :controls="false" style="width:100%" :min="0" v-model="scope.row.prices" />
                </el-form-item>
              </div>
              <div v-if="innertexteFlag == false">
                <div v-if="scope.row.price"> {{ scope.row.price }} </div>
                <el-form-item v-else class="table_form_input" :prop="'SubmitSelectList.' + scope.$index + '.prices'"
                  :rules="rules.prices">
                  <el-input-number style="width:100%" :min="0" :controls="false" v-model="scope.row.prices" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="合计（元）" width="140">
            <template slot-scope="scope">
              <div v-if="innertexteFlag == true"> {{ scope.row.price ? (scope.row.price *
                  scope.row.amounts).toFixed(2) : (scope.row.prices * scope.row.amounts).toFixed(2)
              }} </div>
              <div v-if="innertexteFlag == false">
                <span v-if="scope.row.consPriceAndAmountVo">
                  {{ (scope.row.price * scope.row.amount).toFixed(2) }}
                </span>
                <span v-else>
                  {{ scope.row.price ? (scope.row.price *
                      scope.row.amounts).toFixed(2) : (scope.row.prices * scope.row.amounts).toFixed(2)
                  }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="操作" fixed="right" width="160">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" type="danger" size="small" @click="handledelete(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <!-- ---------------------------------------------------提交及取消【按钮】----------------------------------------------------------- -->
    <div class="form_btn">
      <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      <el-button @click="handleCloseForm">取消</el-button>
    </div>
  </div>
</template>

<script>
import { add, getuserlist, replacementList, equipmentList, listDetail, RegionalList, warehousingPut } from '@/api/deviceConsumable/stock'
import Purchase from './purchase.vue'
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  type: 3, //类别（0采购入库 1盘盈入库 2还回入库 3其他入库）
  purchaseId: '', //采购ID（采购入库，传该参数）
  storehouseId: [], //仓库ID集合,只需传最后一个id，后期需要重组
  remark: "", //备注
  warehousingConsumableVos: [], //物料集合
  // --------------------------------------------------------------------------------------------------------------------
  SubmitSelectList: []//添加物料的勾选后的集合，用于表单验证，后期提交表单需去掉
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'detailedform',
  components: {
    Purchase
  },
  data () {
    return {
      ruleForm: Object.assign({}, ruleForm),
      purchaseOptionsList: ['采购入库', '盘盈入库', '还回入库', '其他入库'],//入库类型数组
      procurementOptionsList: [],// 采购单数组
      storageOptionsList: [],//入库仓库数组
      innertexteFlag: true,// 编辑入库单或者开入库单开关
      warehousingId: '',// 点击编辑带过来的id，后期修改提交的时候拼接进去
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        type: [
          { required: true, message: '请选择采购类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        purchaseId: [
          { required: true, message: '请选择采购单', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        storehouseId: [
          { required: true, message: '请选择入库仓库', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        batch: [
          { required: true, message: '请输入批次', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        amounts: [
          { required: true, message: '请输入入库数量', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入入库数量', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入采购单价', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        prices: [
          { required: true, message: '请输入采购单价', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  // created () {
  //   this.getlist()
  // },
  methods: {
    // 【编辑】按钮查询事件
    refelist (id) {
      if (id) {
        this.warehousingId = id
        this.innertexteFlag = false
        listDetail(id).then(({ data: res }) => {
          console.log(res);
          this.ruleForm.type = res.type * 1
          this.ruleForm.purchaseId = res.purchaseId * 1
          this.ruleForm.remark = res.remark
          RegionalList({ level: 3 }).then(({ data }) => {
            const rule = this.getParentIdList(data, res.storehouseId)
            this.ruleForm.storehouseId = rule
          })
          this.ruleForm.SubmitSelectList = res.warehousingConsumableVos.map(item => {
            return {
              ...item,
              amounts: item.amount,
              prices: item.price
            }
          }) || []
        })
      }
      this.getlist()
    },
    // ----------添加采购品【按钮】 ------------------
    handleAddPurchase () {
      if (this.ruleForm.type == 0) {
        // 采购，只需传采购id
        if (this.ruleForm.purchaseId !== '') {
          this.$refs['purchase_form'].openDialog(this.ruleForm.purchaseId, 0)
        } else {
          this.$message({
            message: '请选择采购单',
            type: 'warning'
          });
        }
      } else {
        // 非采购，只需传仓库id，记得取数组最后一位
        let [end] = [...this.ruleForm.storehouseId].reverse()
        if (end) {
          this.$refs['purchase_form'].openDialog(end, 1)
        } else {
          this.$message({
            message: '请选择入库仓库',
            type: 'warning'
          });
        }
      }
    },
    onInput0_100 (e) {
      this.$message.closeAll();
      // 验证是否是纯数字
      let isNumber = /^\d*$/.test(e.target.value);
      // 过滤非数字
      e.target.value = e.target.value.replace(/\D/g, "");
      if (!isNumber || e.target.value < 0) {
        this.$message.warning("只能输入整数");
      }
      e.target.value = (e.target.value >= 0 && e.target.value.match(/^\d*/g)[0]) || null;
    },
    // 入库仓库数据接口---------------------------------------------------
    async getlist () {
      const { data: res1 } = await equipmentList({ type: '1', status: '0,1', auditStatus: '1' })
      this.procurementOptionsList = res1
      const { data: storage } = await replacementList({ status: 0 })
      // 入库仓库：三级树组重组数据
      const arborescenceList = this.handleTree(storage, "storehouseId");
      arborescenceList.forEach(item => {// 二级数组禁用。不可选
        if (item.children) {
          const arr = item.children.map(j => {
            if (j.children) {
              return Object.assign({}, j, { 'disabled': false })
            } else {
              return Object.assign({}, j, { 'disabled': true })
            }
          })
          item.children = arr
        }
      })
      let ancestors = arborescenceList.map(item => {// 一级数组禁用。不可选
        if (item.children) {
          return Object.assign({}, item, { 'disabled': false })
        } else {
          return Object.assign({}, item, { 'disabled': true })
        }
      })
      this.storageOptionsList = ancestors
    },
    // 入库类型 change 事件--------------------------------------
    handleSelect () {
      this.ruleForm.SubmitSelectList = []
    },
    // 表单采购类型选择器切换
    handleOptions () {
      this.ruleForm.SubmitSelectList = []
    },
    // 接收子组件勾选后的数据
    handleSlectList (val) {
      if (this.innertexteFlag) {
        const arr = [...this.ruleForm.SubmitSelectList, ...val]
        const rule = this.removedup(arr, 'consumableBaseId')
        this.ruleForm.SubmitSelectList = rule.map(item => {
          return {
            ...item,
            batch: '',
            amounts: 1,
            prices: item.price
          }
        })
      } else {
        const rule = val.map(item => {
          return {
            ...item,
            batch: '',
            amounts: 1,
            prices: item.price
          }
        })
        const arrayObject = this.ruleForm.SubmitSelectList.concat(rule)
        this.ruleForm.SubmitSelectList = this.fn2(arrayObject)
      }
    },
    fn2 (arr) {
      const res = new Map();
      return arr.filter(arr => !res.has(arr.consumableBaseId) && res.set(arr.consumableBaseId, arr.consumableBaseId));
    },
    //列表的删除事件
    handledelete (index) {
      this.ruleForm.SubmitSelectList.splice(index, 1)
    },
    // 表单总提交事件
    handleSubmitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let [arr] = [...this.ruleForm.storehouseId].reverse()
          let data = {
            type: this.ruleForm.type,
            remark: this.ruleForm.remark,
            storehouseId: arr,
            warehousingConsumableVos: this.ruleForm.SubmitSelectList.map(item => {
              return {
                consumableBaseId: item.consumableBaseId,//备件物料ID
                batch: item.batch,// 批次号
                price: item.prices,//单价
                amount: item.amounts,//入库数量
              }
            })
          }
          if (this.ruleForm.type == 0) {
            data.purchaseId = this.ruleForm.purchaseId
          }
          console.log('总数据表单', data);
          if (this.innertexteFlag) {
            // --------------------------------------------------新增提交-----重组表格列表提交数据--------------------------------------------
            add(data).then(() => {
              this.ruleForm.SubmitSelectList = []
              this.$emit('form_submit_click')
              this.$message.success('创建成功');
            })
          } else {
            // --------------------------------------------------修改提交-----重组表格列表提交数据--------------------------------------------
            data.warehousingId = this.warehousingId
            warehousingPut(data).then(() => {
              this.ruleForm.SubmitSelectList = []
              this.$emit('form_submit_click')
              this.$message.success('修改成功');
            })
          }

        } else {
          this.$message.error('提交表单验证信息不通过，请重新输入');
        }
      })
    },
    // 表单取消事件
    handleCloseForm () {
      this.$emit('form_submit_click')
    }
  }
}
</script>

<style lang="scss" scoped>
.center_dialog {
  width: 90%;
  margin: 0px auto;
}

.dialog_left {
  width: 100%;

  &_image {
    width: 85px;
  }
}

.dialog_table {
  margin-top: 20px;
}

// .dialog_left>div:nth-child(1){
//   flex:1
// }
.dialog_left>div:nth-child(2) {
  flex: 10;
  margin-left: 10px
}

/* el-descriptions-item 文字居中 */
::v-deep .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.rule-form {
  width: 85%;
  display: flex;
}

.rule_form_audit {
  width: 43%;
  margin: auto;
}

.dialog_btn {
  margin: 10px 45px;
}

.form_btn {
  display: flex;
  justify-content: center;
  margin: 30px auto 20px auto;
}

.table_form_input {
  margin-top: 20px;
}
</style>